package ui.activity;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import Dailog.CommomDialog;
import adapter.TimetableFragmentPrepareAdapter;
import base.BaseBean;
import base.activity.BaseNetActivity;
import bean.BuyRoomBean;
import bean.CourseInfo02Bean;
import bean.JoinRoomBean;
import bean.ScheduleTableBean;
import student.andlei.com.student.R;
import utils.DateUtils;
import utils.GsonUtils;
import utils.ViewUtils;
import view.customcalendar.CalendarActionListener;

/**
 * 班级课表
 */
public class ClassTimeTableActivity extends BaseNetActivity {
    private RecyclerView rcPrepare;
    private TextView tvCurrentDate;
    private ImageView ivNextMonth;
    private ImageView ivLastMonth;
    private CalendarView cdvTimetable;
    private TimetableFragmentPrepareAdapter tfpApater;
    private int schedule_id;
    private ArrayList<CourseInfo02Bean> arrayList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseBack(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        setTitle("班级课表");
    }

    @Override
    public void success(String action, BaseBean baseBean) {
        hideLoadDialog();
        if (baseBean.code == 200) {
            if (action.equals("Schedule/joinRoom")) {
                JoinRoomBean joinRoomBean = (JoinRoomBean) GsonUtils.getInstance(context).parseComplexJArrayByCommon(baseBean, JoinRoomBean.class);
                Bundle bundle = new Bundle();
                bundle.putString("chatroom_id", joinRoomBean.chatroom_id);
                bundle.putString("room_id", joinRoomBean.room_id+"");
                jumpTo(LiveBroadcastActivity.class, bundle);
            }else if(action.equals("schedule/buyRoom")){
                BuyRoomBean roomBean = (BuyRoomBean) GsonUtils.getInstance(context).parseComplexJArrayByCommon(baseBean,BuyRoomBean.class);
                if(roomBean.status.equals("0")){
                    loaddata(DateUtils.getCurrentDateTwo());
                }else {
                    new CommomDialog(ClassTimeTableActivity.this, R.style.dialog, "课时不足，是否购买课时！", new CommomDialog.OnCloseListener() {
                        @Override
                        public void onClick(Dialog dialog, boolean confirm) {
                            if (confirm) {
                                MainActivity.jumpToMineMyClassTime();
                                dialog.dismiss();
                                finish();
                            }
                        }
                    }).setTitle("提示").settPositiveButtonColor(R.color.homepage_titlefont).show();
                }

            } else {
                arrayList.clear();
                String myJson = new Gson().toJson(baseBean.data);//将gson转化为json
                ScheduleTableBean bean = new Gson().fromJson(myJson, ScheduleTableBean.class);
                Map<String, Calendar> map = new HashMap<>();
                for (ScheduleTableBean.Table table : bean.table) {
                    int year = Integer.parseInt(table.room_date.substring(0, 4));
                    //cdvTimetable.getCurYear();
                    int month = Integer.parseInt(table.room_date.substring(5, 7));
                    map.put(getSchemeCalendar(year, month, Integer.parseInt(table.date), 0xFF40db25, "(" + table.count + ")").toString(),
                            getSchemeCalendar(year, month, Integer.parseInt(table.date), 0xFF40db25, "(" + table.count + ")"));
                }
                //此方法在巨大的数据量上不影响遍历性能，推荐使用
                cdvTimetable.setSchemeDate(map);
                //------------------------课时信息
                LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
                rcPrepare.setLayoutManager(linearLayoutManager);
                for (ScheduleTableBean.Rooms rooms : bean.rooms) {
                    CourseInfo02Bean info02Bean = new CourseInfo02Bean();
                    info02Bean.count = rooms.count;
                    info02Bean.end_time = rooms.end_time;
                    info02Bean.is_buy = rooms.is_buy;
                    info02Bean.bag_id = rooms.bag_id;
                    info02Bean.is_over = rooms.is_over;
                    info02Bean.room_id = rooms.room_id;
                    info02Bean.start_time = rooms.start_time;
                    info02Bean.room_name = rooms.room_name;
                    info02Bean.schedule_name = rooms.schedule_name;
                    info02Bean.teacher_name = rooms.teacher_name;
                    info02Bean.room_type = rooms.room_type;
                    info02Bean.status = rooms.status;
                    info02Bean.classroom_status = rooms.classroom_status;
                    info02Bean.video = rooms.video;
                    arrayList.add(info02Bean);
                }
                tfpApater.setNewData(arrayList);
            }
        } else {
            toast(baseBean.msg);
        }
    }

    @Override
    public void error(String action, Throwable e) {
        hideLoadDialog();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_timetable;
    }

    @Override
    protected void findViews() {
        cdvTimetable = getView(R.id.cdv_timetable);
        ivLastMonth = getView(R.id.tv_lastmonth_timetable);
        ivNextMonth = getView(R.id.tv_nextmonth_timetable);
        tvCurrentDate = getView(R.id.tv_currentdate_timetable);
        rcPrepare = getView(R.id.rc_prepare_timetable);
    }

    @Override
    protected void formatViews() {
        //日期选择
        cdvTimetable.setOnDateSelectedListener(calendarActionListener);
        //年份切换
        cdvTimetable.setOnYearChangeListener(calendarActionListener);
        //长按日期
        cdvTimetable.setOnDateLongClickListener(calendarActionListener, false);
        cdvTimetable.setWeeColor(0, R.color.fontcolor);
        tvCurrentDate.setText(cdvTimetable.getCurYear() + "年" + cdvTimetable.getCurMonth() + "月");

        ivLastMonth.setOnClickListener(calendarActionListener);
        ivNextMonth.setOnClickListener(calendarActionListener);
    }

    @Override
    protected void formatData() {
        loaddata(DateUtils.getCurrentDateTwo());
        //------------------------------------
        tfpApater = new TimetableFragmentPrepareAdapter(R.layout.item_rc_date_course_timetable, arrayList);
        //-----课表设置空布局-----------
        tfpApater.setEmptyView(ViewUtils.GetEmptyView(context));
        tfpApater.bindToRecyclerView(rcPrepare);
        tfpApater.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
                switch (view.getId()) {
                    //进入课堂 或 查看录播
                    case R.id.bt_rc_entercourse_timetable:
                        if(arrayList.get(position).is_buy == 1){
                            new CommomDialog(ClassTimeTableActivity.this, R.style.dialog, "课外课时需要购买，消耗一课时！", new CommomDialog.OnCloseListener() {
                                @Override
                                public void onClick(Dialog dialog, boolean confirm) {
                                    if (confirm) {
                                        Map<String,Object> map = new HashMap<>();
                                        map.put("room_id",""+arrayList.get(position).room_id);
                                        post("schedule/buyRoom",map,BaseBean.class,false);
                                        dialog.dismiss();
                                    }
                                }
                            }).setTitle("提示").settPositiveButtonColor(R.color.homepage_titlefont).show();
                            return;
                        }
                        Button mbutton = (Button) view;
                        if (mbutton.getText().toString().trim().equals("查看录播")) {
                            switch (arrayList.get(position).classroom_status) {
                                case 3:
                                    Bundle bundle = new Bundle();
                                    bundle.putString("media_type", "videoondemand");
                                    bundle.putString("decode_type", "software");
                                    // http://ohjdda8lm.bkt.clouddn.com/course/sample1.mp4  "http://jdvodqbt9dzw0.vod.126.net/jdvodqbt9dzw0/f50c3a97-98a7-4467-aefc-82089485e88c.flv"
                                    // http://jdvodqbt9dzw0.vod.126.net/jdvodqbt9dzw0/18c14535-b1e4-4a21-84d2-e560774df0ec.flv
                                    bundle.putString("videoPath", arrayList.get(position).video);
                                    jumpTo(VodActivity.class, bundle);
                                    break;
                                case 4:
                                    new CommomDialog(ClassTimeTableActivity.this, R.style.dialog, "录播正在上传中，请稍等！", new CommomDialog.OnCloseListener() {
                                        @Override
                                        public void onClick(Dialog dialog, boolean confirm) {
                                            if (confirm) {
                                                dialog.dismiss();
                                            }
                                        }
                                    }).setTitle("提示").hideNegativeButton().settPositiveButtonColor(R.color.homepage_titlefont).show();
                                    break;
                            }
                        } else if (mbutton.getText().toString().trim().equals("进入课堂")) {
                            switch (arrayList.get(position).classroom_status) {
                                case 1:
                                    new CommomDialog(ClassTimeTableActivity.this, R.style.dialog, "课程尚未开始，请稍等！", new CommomDialog.OnCloseListener() {
                                        @Override
                                        public void onClick(Dialog dialog, boolean confirm) {
                                            if (confirm) {
                                                dialog.dismiss();
                                            }
                                        }
                                    }).setTitle("提示").hideNegativeButton().settPositiveButtonColor(R.color.homepage_titlefont).show();
                                    break;
                                case 2:
                                    Map<String, String> map = new HashMap<>();
                                    map.put("room_id", "" + arrayList.get(position).room_id);
                                    post("Schedule/joinRoom", map, BaseBean.class, true);
                                    break;
                            }
                        }
                        break;
                    //复习 或 预习
                    case R.id.bt_rc_prepare_timetable:
                        if(arrayList.get(position).is_buy == 1){
                            new CommomDialog(ClassTimeTableActivity.this, R.style.dialog, "课外课时需要购买，消耗一课时！", new CommomDialog.OnCloseListener() {
                                @Override
                                public void onClick(Dialog dialog, boolean confirm) {
                                    if (confirm) {
                                        Map<String,Object> map = new HashMap<>();
                                        map.put("room_id",""+arrayList.get(position).room_id);
                                        post("schedule/buyRoom",map,BaseBean.class,false);
                                        dialog.dismiss();
                                    }
                                }
                            }).setTitle("提示").settPositiveButtonColor(R.color.homepage_titlefont).show();
                            return;
                        }
                        Button button = (Button) view;
                        if (button.getText().equals("复习")) {
                            if (arrayList.get(position).bag_id == 0) {
                                new CommomDialog(ClassTimeTableActivity.this, R.style.dialog, "老师暂无备课包，无法进入复习任务", new CommomDialog.OnCloseListener() {
                                    @Override
                                    public void onClick(Dialog dialog, boolean confirm) {
                                        if (confirm) {
                                            dialog.dismiss();
                                        }
                                    }
                                }).setTitle("提示").hideNegativeButton().settPositiveButtonColor(R.color.homepage_titlefont).show();
                            } else {
                                Bundle bundle = new Bundle();
                                bundle.putInt("room_id", arrayList.get(position).room_id);
                                jumpTo(ReViewTaskActivity.class, bundle);
                            }
                        } else {
                            if (arrayList.get(position).bag_id == 0) {
                                new CommomDialog(ClassTimeTableActivity.this, R.style.dialog, "老师暂无备课包，无法进入预习任务", new CommomDialog.OnCloseListener() {
                                    @Override
                                    public void onClick(Dialog dialog, boolean confirm) {
                                        if (confirm) {
                                            dialog.dismiss();
                                        }
                                    }
                                }).setTitle("提示").hideNegativeButton().settPositiveButtonColor(R.color.homepage_titlefont).show();
                            } else {
                                //格式化时间
                                try{
                                    SimpleDateFormat CurrentTime= new SimpleDateFormat("HH:mm");
                                    Date beginTime  =   CurrentTime.parse(arrayList.get(position).start_time);
                                    Date now =  CurrentTime.parse(DateUtils.getCurrentDatefour());
                                    Date endTime = CurrentTime.parse(arrayList.get(position).end_time);
                                    if(beginTime.getTime()<now.getTime() && now.getTime()<endTime.getTime()){
                                        new CommomDialog(ClassTimeTableActivity.this, R.style.dialog, "正在上课中，请进入课堂", new CommomDialog.OnCloseListener() {
                                            @Override
                                            public void onClick(Dialog dialog, boolean confirm) {
                                                if (confirm) {
                                                    dialog.dismiss();
                                                }
                                            }
                                        }).setTitle("提示").hideNegativeButton().settPositiveButtonColor(R.color.homepage_titlefont).show();

                                    }else {
                                        Bundle bundle_ = new Bundle();
                                        bundle_.putInt("room_id", arrayList.get(position).room_id);
                                        jumpTo(PrePareTaskActivity.class, bundle_);
                                    }
                                }catch (Exception e){

                                }
                            }
                        }
                        break;
                }
            }
        });
    }

    private void loaddata(String date) {
        Map<String, String> map = new HashMap<>();
        map.put("schedule_id", "" + schedule_id);
        map.put("date", date);
        post("schedule/scheduleTable", map, ScheduleTableBean.class, false);
    }

    @Override
    protected void getBundle(Bundle bundle) {
        schedule_id = bundle.getInt("schedule_id");
    }

    @Override
    public void onClick(View view) {

    }

    CalendarActionListener calendarActionListener = new CalendarActionListener() {

        @Override
        public void onYearChange(int year) {

        }

        @Override
        public void onDateSelected(Calendar calendar, boolean isClick) {
            Log.i("calendar", "---->" + isClick);
            tvCurrentDate.setText(calendar.getYear() + "年" + calendar.getMonth() + "月");
            if (isClick) {
                loaddata(calendar.getYear() + "-" + calendar.getMonth() + "-" + calendar.getDay());
            } else {
                if (cdvTimetable.getCurMonth() == calendar.getMonth() && cdvTimetable.getCurYear() == calendar.getYear()) {
                    loaddata(calendar.getYear() + "-" + calendar.getMonth() + "-" + cdvTimetable.getCurDay());
                } else {
                    loaddata(calendar.getYear() + "-" + calendar.getMonth() + "-" + calendar.getDay());
                }
            }


        }

        @Override
        public void onDateLongClick(Calendar calendar) {

        }

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.tv_lastmonth_timetable:
                    cdvTimetable.scrollToPre();
                    break;
                case R.id.tv_nextmonth_timetable:
                    cdvTimetable.scrollToNext();
                    break;
            }
        }
    };

    private Calendar getSchemeCalendar(int year, int month, int day, int color, String text) {
        Calendar calendar = new Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色
        calendar.setScheme(text);
        return calendar;
    }
}
